<?php
/**
 * Append cache key counters to all static source urls (javascript and css files)
 *
 * To Enable this filter, put these lines into your filters.yml file:
 * 
 <pre>
  jfCacheInvalidateStaticSourceUrls:
    class: jfCacheInvalidateStaticSourceUrlsFilter
    param:
      cacheKeyName: cache #name of the url parameter the gets appended to each css/js URL
 </pre>
 *
 * 
 * @package    jfCachePlugin
 * @subpackage lib
 * @author     Jonas Fischer <info@jonasfischer.net>
 * @version    SVN: $Id:$
 */
class jfCacheInvalidateStaticSourceUrlsFilter extends sfFilter
{

  public function execute($filterChain) {

    $filterChain->execute();
  
    $response = $this->context->getResponse();
    $content = $response->getContent();
    $cacheKeyValue = jfCache::getCacheKeyValue(jfCache::$cacheTypes['STATIC_SOURCES']);
    $content = $this->invalidateUrls($content, $cacheKeyValue, $this->getParameter('cacheKeyName', 'cache'));
    $response->setContent($content);
  }
  

  /**
   * Append appendix to all simple css references
   * 
   * @param String $content
   * @param String $appendix
   * 
   * @return String 
   */
  protected function invalidateUrls($content, $cacheKeyValue, $cacheKeyName) {
  	$content = str_replace(
  	  array(
  	    '.css"', 
  	    ".css'",
  	    '.js"',
  	    ".js'"
  	  ), 
  	  array(
  	    '.css?'.$cacheKeyName.'='.$cacheKeyValue.'"', 
  	    '.css?'.$cacheKeyName.'='.$cacheKeyValue."'", 
  	    '.js?'.$cacheKeyName.'='.$cacheKeyValue.'"', 
  	    '.js?'.$cacheKeyName.'='.$cacheKeyValue."'", 
  	  ), 
  	  $content
  	);
  	
    return $content;
  }
}
